import java.util.LinkedList;
import java.util.Queue;

/**
 * @author VernHe
 * @date 2021年05月08日 15:28
 */
public class Solution_019 {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        Queue<ListNode> queue = new LinkedList();
        int count = 0;
        ListNode node = head;
        while (node != null) {
            count++;
            node = node.next;
        }
        if (count == n) {
            head = head.next;
            return head;
        }
        if (count < n) {
            return node;
        } else {
            node = head;
            for (int i = 0; i < count - n - 1; i++) {
                node = node.next;
            }
            System.out.println(node.val);
            if (n == 1) {
                node.next = null;
            } else {
                node.next = node.next.next;
            }
        }

        return head;
    }

    public class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }
}
